# coding: utf-8
# @Time    : 2023/12/18 17:24
# @Author  : gongshuangxi
# @Email   : sxgong@topdatasec.com

import sys

try:
    # python2
    reload(sys)
    sys.setdefaultencoding('utf-8')
except:
    # python3
    pass


class Redprint:
    # name作为uri的组成部分
    def __init__(self, name):
        self.name = name
        # 保存视图函数信息
        self.views = []

    # 实现一个类似蓝图的装饰器
    def route(self, rule, **options):
        def decorator(f):
            # 将f,rule,options作为一个元组保存到列表中
            # 待注册函数中由蓝图实例调用
            self.views.append((f, rule, options))
            return f
        return decorator

    def register(self, bp, url_prefix=None):
        if url_prefix is None:
            url_prefix = "/" + self.name
        # 遍历所有视图函数，通过蓝图实例完成真正的路由注册
        for f, rule, options in self.views:
            endpoint = options.pop("endpoint", f.__name__)
            bp.add_url_rule(url_prefix + rule, endpoint, f, **options)
